import logging
import atexit
from django.utils import timezone
from apscheduler.schedulers.background import BackgroundScheduler
from django_apscheduler.jobstores import DjangoJobStore
from django_apscheduler import util
import pytz

logger = logging.getLogger(__name__)

# 全局调度器变量
scheduler = None

# 将任务函数定义在模块级别
@util.close_old_connections
def daily_settlement_job():
    """每日结算任务"""
    china_tz = pytz.timezone('Asia/Shanghai')
    china_time = timezone.now().astimezone(china_tz)
    logger.info(f"开始执行每日结算任务 - 中国时间: {china_time}")
    try:
        from app.tasks.daily_settlement import DailySettlementService
        result = DailySettlementService.auto_settle_all_employees()
        logger.info(f"每日结算任务完成: {result}")
    except Exception as e:
        logger.error(f"每日结算任务失败: {str(e)}", exc_info=True)

def start_scheduler():
    global scheduler
    
    if scheduler is not None:
        logger.info("调度器已经启动，跳过")
        return
    
    try:
        # 使用UTC时区
        scheduler = BackgroundScheduler(timezone=pytz.UTC)
        scheduler.add_jobstore(DjangoJobStore(), 'default')
        
        # 清理可能存在的旧任务
        try:
            from django_apscheduler.models import DjangoJob
            DjangoJob.objects.filter(id='start_daily_settlement_job').delete()
            logger.info("清理了旧的调度任务")
        except Exception as e:
            logger.warning(f"清理旧任务时出错: {e}")
        
        # 添加任务到调度器 - 使用字符串引用
        scheduler.add_job(
            'app.scheduler:daily_settlement_job',  # 使用字符串引用
            'cron',
            id='start_daily_settlement_job',
            hour=17,  # UTC时间17点 = 中国时间次日01:30
            minute=30,
            timezone=pytz.UTC,
            replace_existing=True,
            max_instances=1,
        )
        
        scheduler.start()
        
        # 显示下次运行时间
        jobs = scheduler.get_jobs()
        for job in jobs:
            next_run = job.next_run_time
            if next_run:
                china_tz = pytz.timezone('Asia/Shanghai')
                china_next_run = next_run.astimezone(china_tz)
                logger.info(f"任务 {job.id} 下次运行时间:")
                logger.info(f"  UTC时间: {next_run}")
                logger.info(f"  中国时间: {china_next_run}")
        
        logger.info("调度器启动成功")
        
        # 注册退出处理
        atexit.register(lambda: scheduler.shutdown() if scheduler else None)
        
    except Exception as e:
        logger.error(f"调度器启动失败: {str(e)}", exc_info=True)

# 在模块加载时调用调度器
start_scheduler()